<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="公司名称" prop="comName" v-if="!currentComId">
        <el-input
          v-model="queryParams.comName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="监控项名称" prop="pointName">
        <el-select
          v-model="queryParams.pointName"
          placeholder="请选择监控项"
          clearable
        >
          <el-option
            v-for="item in pointList"
            :key="item.pointId"
            :label="item.pointName"
            :value="item.pointName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:compoint:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:compoint:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:compoint:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:compoint:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="compointList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" width="60">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        width="180"
        label="公司名称"
        align="center"
        prop="comName"
        v-if="!currentComId"
      /> -->
      <el-table-column width="160" label="监控项名称" align="center" prop="pointName" />
      <el-table-column width="140" label="阈值最大值" align="center" prop="maxValue">
        <template slot-scope="scope">
          <span>{{ scope.row.maxValue }}({{ scope.row.unit }})</span>
        </template>
      </el-table-column>
      <el-table-column
        width="140"
        label="阈值最小值"
        align="center"
        prop="minValue"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.minValue }}({{ scope.row.unit }})</span>
        </template>
      </el-table-column>
      <el-table-column
        width="180"
        label="报警方式"
        align="center"
        prop="alertType"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.alert_type"
            :value="scope.row.alertType ? scope.row.alertType.split(',') : []"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="报警内容模板" align="center" prop="alertMsg">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            width="280"
            trigger="hover"
            :content="`${scope.row.alertMsg}`"
          >
            <span class="template_detail" slot="reference">{{
              scope.row.alertMsg
            }}</span>
          </el-popover>
        </template>
      </el-table-column> -->
      <el-table-column
        width="120"
        label="可报警时间段"
        align="center"
        prop="alertTimeRange"
      />
      <el-table-column
        width="180"
        label="异常持续时间后报警(min)"
        align="center"
        prop="lastTime"
      />
      <el-table-column
        width="160"
        label="报警触发间隔(min)"
        align="center"
        prop="intervalTime"
      />
      <el-table-column
        min-width="140"
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:compoint:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:compoint:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监控项默认规则对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      class="dialog-form"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="监控项" prop="pointId">
          <el-select
            v-model="form.pointId"
            placeholder="请选择监控项"
            :disabled="!!form.id"
            @change="changeMonitor"
          >
            <el-option
              v-for="item in pointList"
              :key="item.pointId"
              :label="item.pointName"
              :value="item.pointId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="公司ID" prop="comId">
          <el-input v-model="form.comId" placeholder="请输入公司ID" />
        </el-form-item> -->
        <el-form-item :label="`阈值最大值(${currentUnit})`" prop="maxValue">
          <el-input
            type="number"
            v-model.number="form.maxValue"
            placeholder="请输入阈值最大值"
          />
        </el-form-item>
        <el-form-item :label="`阈值最小值(${currentUnit})`" prop="minValue">
          <el-input
            type="number"
            v-model.number="form.minValue"
            placeholder="请输入阈值最小值"
          />
        </el-form-item>
        <el-form-item label="报警方式" prop="alertType">
          <el-checkbox-group v-model="form.alertType">
            <el-checkbox
              v-for="dict in dict.type.alert_type"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <el-form-item label="报警内容模板" prop="alertMsg">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.alertMsg"
            placeholder="请输入报警内容模板"
          />
        </el-form-item> -->
        <el-form-item label="可报警时间段">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-select
                v-model="form.startTime"
                placeholder="请选择开始时间"
                clearable
              >
                <el-option
                  v-for="item in Array.from(new Array(24), (_, i) => i)"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-select
                v-model="form.endTime"
                placeholder="请选择结束时间"
                clearable
              >
                <el-option
                  v-for="item in Array.from(new Array(24), (_, i) => i)"
                  :key="item"
                  :label="item"
                  :value="item"
                  :disabled="item <= form.startTime"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="异常持续时间后报警(min)" prop="lastTime">
          <el-input
            :min="0"
            type="number"
            v-model.number="form.lastTime"
            placeholder="请输入异常持续时间后报警，单位min"
          />
        </el-form-item>
        <el-form-item label="报警触发间隔(min)" prop="intervalTime">
          <el-input
            :min="0"
            type="number"
            v-model.number="form.intervalTime"
            placeholder="请输入每次报警触发的间隔，单位min"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompoint,
  getCompoint,
  delCompoint,
  addCompoint,
  updateCompoint,
  listPoint,
} from "@/api/system/compoint";

export default {
  name: "Compoint",
  dicts: ["alert_type"],
  data() {
    return {
      // 单位
      currentUnit: "",
      pointList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控项默认规则表格数据
      compointList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        comName: "",
        pageNum: 1,
        pageSize: 10,
        comId: this.$store.state.user.uInfo.comId,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pointId: [{ required: true, message: "请选择监控项", trigger: "blur" }],
        maxValue: [
          // { required: true, message: "阈值最大值必填", trigger: "blur" },
          { type: "number", message: "阈值最大值必需是数字" },
        ],
        minValue: [
          // { required: true, message: "阈值最小值必填", trigger: "blur" },
          { type: "number", message: "阈值最小值必需是数字" },
          {
            validator: (rule, value, callback) => {
              if (value >= this.form.maxValue && this.form.maxValue) {
                callback(new Error("阈值最小值不能大于阈值最大值"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        alertType: [
          { required: true, message: "报警方式必填", trigger: "blur" },
        ],
        // alertMsg: [
        //   { required: true, message: "报警内容模板必填", trigger: "blur" },
        // ],
        // startTime: [
        //   { required: true, message: "开始时间必填", trigger: "blur" },
        // ],
        // endTime: [{ required: true, message: "结束时间必填", trigger: "blur" }],
      },
      currentComId: this.$store.state.user.uInfo.comId,
    };
  },
  created() {
    this.getPointList();
    this.getList();
  },
  methods: {
    // 新增时监控项选择事件
    changeMonitor(e) {
      console.log(e);
      const matchMonitor = this.pointList.find((item) => item.pointId === e);
      if (matchMonitor) {
        this.currentUnit = matchMonitor.unit;
      }
    },
    getPointList() {
      this.loading = true;
      listPoint().then((response) => {
        this.pointList = response.rows;
        this.loading = false;
      });
    },
    /** 查询监控项默认规则列表 */
    getList() {
      this.loading = true;
      listCompoint(this.queryParams).then((response) => {
        this.compointList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // id: null,
        pointId: null,
        comId: null,
        maxValue: null,
        minValue: null,
        alertType: [],
        alertMsg: null,
        // alertTimeRange: null,
        // delFlag: null,
        // createBy: null,
        // createTime: null,
        // updateBy: null,
        // updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.currentUnit = "";
      this.title = "添加监控项默认规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.currentUnit = row.unit;
      getCompoint(id).then((response) => {
        this.form = {
          ...response.data,
          startTime: response.data.alertTimeRange?.split("-")[0],
          endTime: response.data.alertTimeRange?.split("-")[1],
        };
        this.form.alertType = this.form.alertType.split(",");
        // setTimeout(() => {
        //   if (this.form.alertTimeRange) {
        //     this.form.startTime =
        //       this.form.alertTimeRange.split("-")[0] + ":00";
        //     this.form.endTime = this.form.alertTimeRange.split("-")[1] + ":00";
        //   }
        // }, 500);
        this.open = true;
        this.title = "修改监控项默认规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.form.maxValue && !this.form.minValue) {
        this.$message({
          message: "阈值最大值最小值必须填写一个",
          type: "warning",
        });
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.comId = this.$store.state.user.uInfo.comId;
          this.form.alertTimeRange =
            this.form.startTime && this.form.endTime
              ? `${this.form.startTime}-${this.form.endTime}`
              : null;
          this.form.alertType = this.form?.alertType?.join?.(",") ?? "";
          if (this.form.id != null) {
            updateCompoint(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch((err) => {
                this.form.alertType = this.form.alertType.split(",");
              });
          } else {
            addCompoint(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch((err) => {
                this.form.alertType = this.form.alertType.split(",");
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除监控项默认规则编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCompoint(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/compoint/export",
        {
          ...this.queryParams,
        },
        `compoint_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.dialog-form >>> .el-date-editor {
  width: 100%;
}
.dialog-form >>> .el-select {
  width: 100%;
}
.line {
  text-align: center;
}
.template_detail {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
</style>
